﻿using RMS.Common;
using RMS.EF.Model;
using RMS.EF.Model.Common;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;

namespace RMS.BLL
{
    public class UserBll
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model_e">新增的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Add(RMS_User_Extend model_e)
        {
            var result = new CommonOutPutVm();
            RMS_User model = ToolsHelper.ConverToTEntity<RMS_User>(model_e);
            using (var db = new RMSEntities())
            {
                #region 验证
                bool exist = db.RMS_User.Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && p.UserName == model.UserName);
                if (exist)
                {
                    result.Message = "用户名已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.RMS_User.Add(model);
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "新增管理员保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model_e">修改后的模型实体</param>
        /// <returns></returns>
        public CommonOutPutVm Updata(RMS_User_Extend model_e)
        {
            var result = new CommonOutPutVm();
            RMS_User model = ToolsHelper.ConverToTEntity<RMS_User>(model_e);
            using (var db = new RMSEntities())
            {
                #region 验证
                bool exist = db.RMS_User.Any(p => p.Deleted == (int)E_Deleted.Normal && p.Id != model.Id && p.UserName == model.UserName);
                if (exist)
                {
                    result.Message = "用户名已经存在";
                    return result;
                }
                #endregion
                #region 保存
                db.Entry(model).State = EntityState.Modified;
                db.Entry(model).Property(p => p.Password).IsModified = false;
                db.Entry(model).Property(p => p.Deleted).IsModified = false;
                db.Entry(model).Property(p => p.CreationTime).IsModified = false;
                db.Entry(model).Property(p => p.CreationUser).IsModified = false;
                int row = db.SaveChanges();
                if (row != 1)
                {
                    result.Message = "修改管理员保存异常：" + model.Id;
                    return result;
                }
                #endregion
            }
            result.IsSuccess = true;
            result.Message = "保存成功";
            return result;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id">数据Id字符串"','"分隔</param>
        /// <returns></returns>
        public CommonOutPutVm Delete(string id)
        {
            var result = new CommonOutPutVm();
            #region 验证
            if (string.IsNullOrWhiteSpace(id))
            {
                result.Message = "请选择一条数据";
                return result;
            }
            #endregion
            using (var db = new RMSEntities())
            {
                db.Database.ExecuteSqlCommand("update RMS_User set Deleted=1 where Id in ('" + id + "')");
                db.SaveChanges();
            }
            result.IsSuccess = true;
            result.Message = "删除成功";
            return result;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="page">分页参数</param>
        /// <param name="searchModel">搜索条件类</param>
        /// <returns></returns>
        public CommonOutPutVm GetByPage(PageParams page, S_RMS_User searchModel)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_User.Where(p => p.Deleted == (int)E_Deleted.Normal);
                #region where
                if (!string.IsNullOrWhiteSpace(searchModel.SearchValue))
                {
                    q = q.Where(p => p.UserName.Contains(searchModel.SearchValue) || p.NickName.Contains(searchModel.SearchValue));
                }
                if (searchModel.Status != E_Status.All)
                {
                    q = q.Where(p => p.Status == (int)searchModel.Status);
                }
                #endregion
                page.Total = q.Count();
                #region order by
                if (string.IsNullOrWhiteSpace(page.Order))
                {
                    q = q.OrderBy(p => p.CreationTime);
                }
                else
                {
                    var orderExpression = string.Format("{0} {1}", page.Order, page.OrderType);
                    q = q.OrderBy(orderExpression);
                }
                #endregion
                q = q.Skip(page.Start).Take(page.Length);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 根据Id获取未删除的实体
        /// </summary>
        /// <param name="id">Id主键</param>
        /// <returns></returns>
        public CommonOutPutVm GetById(string id)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var data = db.RMS_User.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
                if (data == null)
                {
                    result.Message = "管理员不存在";
                    return result;
                }
                result.Data = ToolsHelper.ConverToTEntity<RMS_User_Extend>(data);
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 根据用户获取角色关联信息
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <returns></returns>
        public CommonOutPutVm Get_UserRole_ByUserId(string id)
        {
            var result = new CommonOutPutVm();
            using (var db = new RMSEntities())
            {
                var q = db.RMS_User_Role.Where(p => p.Deleted == (int)E_Deleted.Normal && p.UserId == id).OrderBy(p => p.RoleId);
                result.Data = q.ToList();
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 关联角色
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="roleId">角色Id集合</param>
        /// <param name="userId">操作用户Id</param>
        /// <returns></returns>
        public CommonOutPutVm Relation_Role(string id, string roleIds, string userId)
        {
            CommonOutPutVm result = new CommonOutPutVm();
            #region 角色Id转成集合
            var roleId = new List<string>();
            if (!string.IsNullOrWhiteSpace(roleIds))
            {
                roleId = roleIds.Split(',').ToList();
            }
            #endregion
            using (var db = new RMSEntities())
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        DateTime now = DateTime.Now;
                        #region 根据角色Id删除所有关联
                        string sql = @"update RMS_User_Role set Deleted=1, LastUpdateTime=@now, LastUpdateUser=@userId where UserId=@id";
                        db.Database.ExecuteSqlCommand(sql,
                            new SqlParameter("@id", id),
                            new SqlParameter("@now", now),
                            new SqlParameter("@userId", userId));
                        db.SaveChanges();
                        #endregion
                        #region 循环处理
                        for (int i = 0; i < roleId.Count; i++)
                        {
                            var item = roleId[i];
                            //存在验证
                            var exist = db.RMS_User_Role.Any(p => p.UserId == id && p.RoleId == item);
                            #region 存在就修改删除标记
                            if (exist)
                            {
                                sql = @"update RMS_User_Role set Deleted=0, LastUpdateTime=@now, LastUpdateUser=@userId where UserId=@id and RoleId=@roleId";
                                db.Database.ExecuteSqlCommand(sql,
                                    new SqlParameter("@id", id),
                                    new SqlParameter("@roleId", item),
                                    new SqlParameter("@now", now),
                                    new SqlParameter("@userId", userId));
                            }
                            #endregion
                            #region 不存在就新增记录
                            else
                            {
                                var model = new RMS_User_Role()
                                {
                                    Id = Guid.NewGuid().ToString(),
                                    UserId = id,
                                    RoleId = item,
                                    Deleted = (int)E_Deleted.Normal,
                                    CreationTime = now,
                                    CreationUser = userId,
                                    LastUpdateTime = now,
                                    LastUpdateUser = userId
                                };
                                db.RMS_User_Role.Add(model);
                            }
                            #endregion
                            db.SaveChanges();
                        }
                        #endregion
                        tran.Commit();
                        result.IsSuccess = true;
                        result.Message = "保存成功";
                    }
                    catch (Exception e)
                    {
                        tran.Rollback();
                        throw e;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="user">登录信息</param>
        /// <returns></returns>
        public CommonOutPutVm Login(RMS_User user)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            if (string.IsNullOrWhiteSpace(user.UserName))
            {
                result.Message = "请输入用户名！";
                return result;
            }
            if (string.IsNullOrWhiteSpace(user.Password))
            {
                result.Message = "请输入密码！";
                return result;
            }
            #endregion
            using (var db = new RMSEntities())
            {
                var loginUser = db.RMS_User.FirstOrDefault(p => p.UserName == user.UserName && p.Deleted == (int)E_Deleted.Normal && p.Status == (int)E_Status.Enable);
                #region 登录验证
                if (loginUser == null)
                {
                    result.Message = "用户名不存在！";
                    return result;
                }
                if (loginUser.Password != user.Password.ToMD5())
                {
                    result.Message = "密码不正确！";
                    return result;
                }
                #endregion
                result.Data = loginUser;
            }
            result.IsSuccess = true;
            return result;
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <returns></returns>
        public CommonOutPutVm ResetPwd(string id)
        {
            var result = new CommonOutPutVm();
            #region 验证
            if (string.IsNullOrWhiteSpace(id))
            {
                result.Message = "请选择管理员";
                return result;
            }
            #endregion
            #region 从config里获取默认密码并重置
            using (var db = new RMSEntities())
            {
                var user = db.RMS_User.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
                #region 验证
                if (user == null)
                {
                    result.Message = "用户不存在";
                    return result;
                }
                #endregion
                db.Entry(user).State = EntityState.Unchanged;
                ConfigBll config = new ConfigBll();
                var cResult = config.GetEnableByKey("A1");
                string defaultpwd = cResult.Data;
                user.Password = defaultpwd.ToMD5();
                db.Entry(user).Property(p => p.Password).IsModified = true;
                db.SaveChanges();
            }
            #endregion
            result.IsSuccess = true;
            result.Message = "重置密码成功";
            return result;
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="orgPwd">原始密码</param>
        /// <param name="newPwd">新密码</param>
        /// <param name="rePwd">确认密码</param>
        /// <returns></returns>
        public CommonOutPutVm EditPassword(string id, string orgPwd, string newPwd, string rePwd)
        {
            var result = new CommonOutPutVm();
            #region 输入验证
            if (string.IsNullOrWhiteSpace(orgPwd))
            {
                result.Message = "请输入原密码";
                return result;
            }
            if (newPwd.Length < 6 || newPwd.Length > 50)
            {
                result.Message = "密码长度不能小于6位";
                return result;
            }
            if (newPwd != rePwd)
            {
                result.Message = "两次输入的密码不一致";
                return result;
            }
            #endregion
            #region 验证原始密码并修改新密码
            using (var db = new RMSEntities())
            {
                var user = db.RMS_User.AsNoTracking().FirstOrDefault(p => p.Id == id && p.Deleted == (int)E_Deleted.Normal);
                #region 验证
                if (user == null)
                {
                    result.Message = "用户不存在";
                    return result;
                }
                if (orgPwd.ToMD5() != user.Password)
                {
                    result.Message = "原密码不正确";
                    return result;
                }
                #endregion
                db.Entry(user).State = EntityState.Unchanged;
                user.Password = newPwd.ToMD5();
                db.Entry(user).Property(p => p.Password).IsModified = true;
                db.SaveChanges();
            }
            #endregion
            result.IsSuccess = true;
            return result;
        }
    }
}
